(function($) {
	$('#gallery-modal').modal({'show': false});
	$('#gallery-modal').on('hidden.bs.modal', function(){
    	$('#view-image').remove();
    });
    
	$('ul.gallery li img').on('click',function(){
        var src = $(this).data('src');
        var img = '<img src="' + src + '" width="100%" />';
        
        var index = $(this).parent('li').index();
        var total = $('ul.gallery li').length; 
        var html = '<div id="view-image" style="display:none;">';
        html += img;                
        html += '<div style="height:25px;clear:both;display:block;">';
        if(total >= (index+2)){
        	html += '<a class="controls next" href="javascript:void(0)" data-num="'+ (index+2) + '">' + $('#gallery-modal').data('next') + ' &raquo;</a>';
        }
        else{
        	html += '<a class="controls next" href="javascript:void(0)" style="display:none;" data-num="'+ (index+2) + '">' + $('#gallery-modal').data('next') + ' &raquo;</a>';
        }
        
        if(index > 0){
        	html += '<a class="controls previous" href="javascript:void(0)" data-num="' + (index) + '">&laquo; ' + $('#gallery-modal').data('prev') + '</a>';
        }
        else {
        	html += '<a class="controls previous" href="javascript:void(0)" style="display:none;" data-num="' + (index) + '">&laquo; ' + $('#gallery-modal').data('prev') + '</a>';
        }
        html += '</div>';
        html += '</div>';
        
        $('#gallery-modal .loading').show();
    	$('#gallery-modal .modal-body').append(html);
    	$("#view-image img").on('load', function() {
    		$('#gallery-modal .loading').hide();
    		$('#view-image').show();
    	});
    	
        $('#gallery-modal').modal('show');
   	});
   
   	$(document).on('click', 'a.controls', function(){
		var index = $(this).data('num');
        var src = $('ul.gallery li:nth-child('+ index +') img').data('src');             
        
        $('#gallery-modal .loading').show();
        $('#view-image').hide();
        $('#view-image img').attr('src', src);
        
        var newPrevIndex = parseInt(index) - 1; 
        var newNextIndex = parseInt(newPrevIndex) + 2; 
        
        if($(this).hasClass('previous')) {               
            $(this).data('num', newPrevIndex); 
            $('a.next').data('num', newNextIndex);
        } else {
            $(this).data('num', newNextIndex); 
            $('a.previous').data('num', newPrevIndex);
        }
        
        var total = $('ul.gallery li').length + 1; 
        //hide next button
        if(total === newNextIndex){
            $('a.next').hide();
        }else{
            $('a.next').show();
        }            
        //hide previous button
        if(newPrevIndex === 0){
            $('a.previous').hide();
        }else{
            $('a.previous').show();
        }

        return false;
	});
})(jQuery);